package com.song.tools.songtest.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.song.tools.core.exception.BusinessException;
import com.song.tools.core.exception.ExceptionCodeEnum;
import com.song.tools.core.util.ObjectUtils;
import com.song.tools.mvc.request.BatchIdRequest;
import com.song.tools.mvc.request.PageRequest;
import com.song.tools.mvc.response.DeleteResponse;
import com.song.tools.mvc.response.PageResponse;
import com.song.tools.mvc.validator.ValidationException;
import com.song.tools.mvc.validator.ValidationResult;
import com.song.tools.songtest.beans.bo.DictionaryDetailBo;
import com.song.tools.songtest.beans.poi.DictionaryDetailExportDto;
import com.song.tools.songtest.beans.poi.DictionaryDetailImportDto;
import com.song.tools.songtest.beans.query.DictionaryDetailQuery;
import com.song.tools.songtest.beans.request.DictionaryDetailQueryRequest;
import com.song.tools.songtest.beans.request.DictionaryDetailSaveRequest;
import com.song.tools.songtest.beans.request.DictionaryDetailUpdateRequest;
import com.song.tools.songtest.beans.response.DictionaryDetailDeleteResponse;
import com.song.tools.songtest.beans.response.DictionaryDetailQueryResponse;
import com.song.tools.songtest.beans.response.DictionaryDetailSaveResponse;
import com.song.tools.songtest.beans.response.DictionaryDetailUpdateResponse;
import com.song.tools.songtest.config.DistributedSnowflake;
import com.song.tools.songtest.convertor.DictionaryDetailConvertor;
import com.song.tools.songtest.dao.entity.DictionaryDetail;
import com.song.tools.songtest.manager.DictionaryDetailManager;
import com.song.tools.songtest.service.DictionaryDetailService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典明细表 服务实现类
 * </p>
 *
 * @author song tools
 * @since 2024-07-12
 */
@Slf4j
@Service
public class DictionaryDetailServiceImpl implements DictionaryDetailService {

    @Resource
    private DictionaryDetailManager dictionaryDetailManager;

    @Resource
    private DictionaryDetailConvertor dictionaryDetailConvertor;

    @Resource
    private DistributedSnowflake distributedSnowflake;

    private static final Map<String, SFunction<DictionaryDetail, ?>> COLUMNS_FUNCTION_MAP;
    static {
        COLUMNS_FUNCTION_MAP = Map.of(
                "id", DictionaryDetail::getId,
                "dictionaryDetailId", DictionaryDetail::getDictionaryDetailId
        );
    }


    /**
     * 通过主键列表批量删除
     *
     * @param request 主键列表请求体
     * @return 删除结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DictionaryDetailDeleteResponse deleteByPrimaryKeys(BatchIdRequest<Long> request) {
        List<Long> primaryKeys = request.getIds();
        if (CollUtil.isEmpty(primaryKeys)) {
            throw new BusinessException(ExceptionCodeEnum.PARAM_NOT_NULL);
        }

        // 如果列表很大，考虑分批删除以减轻数据库压力
        int batchSize = 100; // 每批处理100条
        int totalDeleted = 0; // 记录总共删除的行数

        for (int i = 0; i < primaryKeys.size(); i += batchSize) {
            int toIndex = Math.min(i + batchSize, primaryKeys.size());
            List<Long> batchKeys = primaryKeys.subList(i, toIndex);

            int rows = dictionaryDetailManager.deleteBatchByPrimaryKeys(batchKeys);
            totalDeleted += rows;
        }

        DictionaryDetailDeleteResponse response = new DictionaryDetailDeleteResponse();
        response.setDeleted(totalDeleted > 0 ? DeleteResponse.DELETED_SUCCESS : DeleteResponse.DELETED_FAIL);
        return response;
    }


    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public DictionaryDetailQueryResponse getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        DictionaryDetailBo dictionaryDetailBo = dictionaryDetailManager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, DictionaryDetail::getId));
        return dictionaryDetailConvertor.entityBoToQueryResponse(dictionaryDetailBo);
    }

    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<DictionaryDetailQueryResponse> list(DictionaryDetailQueryRequest request) {
        DictionaryDetailQuery dictionaryDetailQuery = dictionaryDetailConvertor.queryRequestToQuery(request);
        if (ObjectUtils.isNotEmpty(dictionaryDetailQuery)) {
            List<DictionaryDetailBo> dictionaryDetailList = dictionaryDetailManager.list(dictionaryDetailQuery);
            if (ObjectUtils.isNotEmpty(dictionaryDetailList)) {
                return dictionaryDetailList.stream()
                        .map(dictionaryDetailConvertor::entityBoToQueryResponse)
                        .filter(ObjectUtils::isNotEmpty)
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查询信息（分页）
     *
     * @param request 请求
     * @return PageResponse 响应
     */
    @Override
    public PageResponse<DictionaryDetailQueryResponse> listPages(PageRequest<DictionaryDetailQueryRequest> request) {
        try {
            // 分页查询
            IPage<DictionaryDetailBo> dictionaryDetailPage = dictionaryDetailManager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(dictionaryDetailPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param dictionaryDetailPage 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<DictionaryDetailQueryResponse> safelyConvertPage(IPage<DictionaryDetailBo> dictionaryDetailPage) {
        if (dictionaryDetailPage == null || dictionaryDetailPage.getRecords() == null) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<DictionaryDetailQueryResponse> responses = dictionaryDetailPage.getRecords().parallelStream()
            .map(dictionaryDetailBo -> dictionaryDetailConvertor.entityBoToQueryResponse(dictionaryDetailBo))
            .collect(Collectors.toList());

        return PageResponse.convertPage(dictionaryDetailPage, responses);
    }


    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    private PageRequest<DictionaryDetailQuery> transformToQuery(PageRequest<DictionaryDetailQueryRequest> request) {
        DictionaryDetailQuery dictionaryDetailQuery = dictionaryDetailConvertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), dictionaryDetailQuery);
    }


    /**
     * 新增
     *
     * @param saveRequest 请求入参
     * @return 响应
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DictionaryDetailSaveResponse save(DictionaryDetailSaveRequest saveRequest) {
        // 校验请求入参
        ValidationResult validationResult = validateOnSave(saveRequest);
        if (!validationResult.isValid()) {
            throw ValidationException.message(validationResult.getErrorMessage());
        }

        // 根据入参封装 BO对象
        DictionaryDetailBo dictionaryDetailBo = dictionaryDetailConvertor.saveRequestToEntityBo(saveRequest);

        // 数据库操作：插入数据
        int rows = dictionaryDetailManager.save(dictionaryDetailBo);
        // 设置字典明细ID
        if (ObjectUtils.isEmpty(saveRequest.getDictionaryDetailId())) {
            saveRequest.setDictionaryId(distributedSnowflake.nextIdStr());
        }

        // 处理插入结果
        boolean saveSuccess = rows > 0;
        // 新增数据成功，返回结果
        if (saveSuccess) {
            // 修改后的数据通过数据库查询返回
            DictionaryDetailBo savedDictionaryDetailBo = dictionaryDetailManager.getOneByUniqueKey(dictionaryDetailBo.getId(), DictionaryDetail::getId);
            return dictionaryDetailConvertor.entityBoToSaveResponse(savedDictionaryDetailBo);
        }

        // 新增数据失败，抛出异常
        throw new BusinessException(ExceptionCodeEnum.CREATE_ERROR);
    }

    /**
    * 修改
    *
    * @param updateRequest 请求
    * @return 响应
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DictionaryDetailUpdateResponse update(DictionaryDetailUpdateRequest updateRequest) {
        // 校验请求入参
        ValidationResult validationResult = validateOnUpdate(updateRequest);
        if (!validationResult.isValid()) {
            throw ValidationException.message(validationResult.getErrorMessage());
        }

        // 根据入参封装 BO对象
        DictionaryDetailBo dictionaryDetailBo = dictionaryDetailConvertor.updateRequestToEntityBo(updateRequest);

        // 数据库操作：修改数据
        int rows = dictionaryDetailManager.updateByPrimaryKey(dictionaryDetailBo);

        // 处理修改结果
        boolean updateSuccess = rows > 0;
        // 修改数据成功，返回结果
        if (updateSuccess) {
            // 修改后的数据通过数据库查询返回
            DictionaryDetailBo updatedDictionaryDetailBo = dictionaryDetailManager.getOneByUniqueKey(dictionaryDetailBo.getId(), DictionaryDetail::getId);
            return dictionaryDetailConvertor.entityBoToUpdateResponse(updatedDictionaryDetailBo);
        }

        // 修改数据失败，抛出异常
        throw new BusinessException(ExceptionCodeEnum.UPDATE_ERROR);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file) {
        try {
            // 默认每次会读取100条数据
            EasyExcel.read(file.getInputStream(), DictionaryDetailImportDto.class, new PageReadListener<DictionaryDetailImportDto>(importDtos -> {
                ValidationResult validationResult = validateOnImport(importDtos);
                if (!validationResult.isValid()) {
                    throw ValidationException.message(validationResult.getErrorMessage());
                }

                // 数据转换
                List<DictionaryDetailBo> dictionaryDetailBos = dictionaryDetailConvertor.importDtoToEntityBo(importDtos);
                // 保存到数据库
                dictionaryDetailManager.saveBatch(dictionaryDetailBos);
            })).sheet().doRead();
        } catch (Exception e) {
            log.warn("上传文件异常 {}", e.getLocalizedMessage(), e);
            throw new BusinessException(ExceptionCodeEnum.IMPORT_ERROR);
        }
    }


    @Override
    public void importTpl(HttpServletResponse response) {
        try {
            // 设置相应格式
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setCharacterEncoding("utf-8");

            // URLEncoder.encode 可以防止中文乱码
            String filename = "字典明细表_导入模版_" + LocalDateTime.now();
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + filename + ".xlsx");
            try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), DictionaryDetailImportDto.class).autoCloseStream(false).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
                excelWriter.write(Collections.emptyList(), writeSheet);
            }
        } catch (Exception e) {
            log.warn("导出模版异常 {}", e.getLocalizedMessage(), e);
            throw new RuntimeException(e);
        }
    }


    @Override
    public void export(HttpServletResponse response, DictionaryDetailQueryRequest queryRequest) throws IOException {
        try {
            // 设置相应格式
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setCharacterEncoding("utf-8");

            // 分页请求
            PageRequest<DictionaryDetailQueryRequest> pageRequest = new PageRequest<>();
            pageRequest.setData(queryRequest);
            pageRequest.setPageSize(500);
            pageRequest.setPageNum(1);

            PageRequest<DictionaryDetailQuery> pageQuery = transformToQuery(pageRequest);

            // URLEncoder.encode 可以防止中文乱码
            String filename = "字典明细表_" + LocalDateTime.now();
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + filename + ".xlsx");
            try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), DictionaryDetailExportDto.class).autoCloseStream(false).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();

                long totalPage = 0;
                while (true) {
                    // 从数据库中读取数据
                    IPage<DictionaryDetailBo> dictionaryDetailPage = dictionaryDetailManager.page(pageQuery);
                    if (dictionaryDetailPage.getTotal() > 100_000) {
                        throw new BusinessException(ExceptionCodeEnum.EXPORT_TOO_MUCH);
                    }
                    if (dictionaryDetailPage.getPages() != 0) {
                        totalPage = dictionaryDetailPage.getPages();
                    }

                    // 查到的结果为空
                    if (dictionaryDetailPage.getRecords().isEmpty()) {
                        break;
                    }

                    // 写入到 excel 中
                    List<DictionaryDetailExportDto> exportVos = dictionaryDetailPage.getRecords().stream().map(dictionaryDetailConvertor::entityBoToExportDto).collect(Collectors.toList());
                    excelWriter.write(exportVos, writeSheet);

                    // 没有下一页，跳出循环
                    if (dictionaryDetailPage.getCurrent() >= totalPage) {
                        break;
                    }

                    // 请求下一页
                    pageRequest.setPageNum(pageRequest.getPageNum() + 1);
                }
            }
        } catch (Exception e) {
            log.warn("导出文件异常 {}", e.getLocalizedMessage(), e);
            throw new BusinessException(ExceptionCodeEnum.EXPORT_ERROR);
        }
    }
}
